package com.ymm.driver.core.listener.mq;

import com.alibaba.fastjson.JSON;
import com.ymm.driver.api.constants.Entity.ComplaintOpsLogEntity;
import com.ymm.driver.api.constants.Entity.NoticeEntity;
import com.ymm.driver.api.facade.DriverNoticeService;
import com.ymm.driver.core.constants.ComplaintOpsEnum;
import com.ymm.driver.core.constants.MessgeStatusEnum;
import com.ymm.driver.core.constants.NoticeTypeEnum;
import com.ymm.driver.core.listener.mq.msg.ComplaintCompleteMsg;
import com.ymm.driver.core.websocket.WebSocket;
import com.ymm.driver.dao.mapper.DriverComplaintOpsLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Objects;

@Slf4j
@Component
@RocketMQMessageListener(topic = "${mq.topic.complaint}", consumerGroup = "${mq.consumer.groupname.complaint.complete}", selectorExpression = "complete", maxReconsumeTimes = 3)
public class ComplaintCompleteMsgConsumer implements RocketMQListener<MessageExt> {
    @Resource
    private DriverComplaintOpsLogMapper driverComplaintOpsLogMapper;

    @Resource
    private WebSocket webSocket;

    @Resource
    private DriverNoticeService driverNoticeService;


    @Override
    public void onMessage(MessageExt messageExt) {
        //解析消息内容
        String body = new String(messageExt.getBody(), StandardCharsets.UTF_8);
        ComplaintCompleteMsg complaintCompleteMsg = JSON.parseObject(body, ComplaintCompleteMsg.class);
        if (Objects.isNull(complaintCompleteMsg)) {
            log.info("cargoPullOffMsg为空！");
            return;
        }
        Long complaintsId = complaintCompleteMsg.getComplaintsId();
        Long driverId = complaintCompleteMsg.getComplaintId();
        Integer opsType = ComplaintOpsEnum.COMPLETE.getCode();
        if (Objects.isNull(complaintsId) || Objects.isNull(driverId)) {
            log.info("参数为空！");
            return;
        }

        ComplaintOpsLogEntity complaintOpsLog = new ComplaintOpsLogEntity();
        complaintOpsLog.setComplaintsId(complaintsId);
        complaintOpsLog.setDriverId(driverId);
        complaintOpsLog.setOrderId(complaintCompleteMsg.getOrderId());
        complaintOpsLog.setOpsType(opsType);
        complaintOpsLog.setOpsPersonType(complaintCompleteMsg.getOpsPersonType());
        complaintOpsLog.setOpsPersonId(complaintCompleteMsg.getOpsPersonId());
        complaintOpsLog.setCreateTime(new Date());
        complaintOpsLog.setUpdateTime(new Date());
        complaintOpsLog.setExecutionStatus(MessgeStatusEnum.IN_EXECUTION.getCode());

        //保存到数据库
        try {
            driverComplaintOpsLogMapper.add(complaintOpsLog);
        } catch (Exception e) {
            if (!Objects.isNull(driverComplaintOpsLogMapper.getLogIdByDriverIdAndComplaintsIdAndOpsType(driverId, complaintsId, opsType))) {
                log.info(complaintOpsLog.getLogId() + "消息已经被消费过");
                return;
            } else {
                log.info("数据库错误");
                //重试
                throw e;
            }
        }

        //投递通知
        try {
            NoticeEntity notice = new NoticeEntity();
            notice.setDriverId(driverId);
            notice.setContent("您的申诉处理完成。");
            notice.setFromPersonType(complaintCompleteMsg.getOpsPersonType());
            notice.setFromPersonId(complaintCompleteMsg.getOpsPersonId());
            notice.setNoticeType(NoticeTypeEnum.AGENT_NOTICE.getCode());
            notice.setAdditionalInformation("{\"orderId\":" + complaintCompleteMsg.getOrderId() + ", \"compaintsId\":" + complaintsId + "}");
            driverNoticeService.saveNotice(notice);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //WebSocket通知
        try {
            webSocket.sendOnMessage(driverId, "您的申诉处理完成！");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //设置业务执行状态为完成
        driverComplaintOpsLogMapper.updateExecutionStatusByLogId(complaintOpsLog.getLogId(), MessgeStatusEnum.COMPLETED.getCode());

    }
}
